<?php
/**
 * ===============================================
 * 版权所有 2019-2050 青岛铁锤科技有限公司，并保留所有权利。
 * 网站地址: http://www.huaxianling.com
 * ===============================================
 * Author: Happy dong
 * Created Time: 2019-09-26 10:06
 *
 * Version: 2.0
 */

namespace App\Modules\System\Repositories;


use App\Models\AmountFlow;
use App\Modules\System\Criterias\getContributionOrderListCriteria;
use Flower\Core\Repository\Eloquent\BaseRepository;
use Illuminate\Support\Facades\DB;

class AmountFlowRepository extends BaseRepository
{
	public function model()
	{
		return AmountFlow::class;
	}


	/**
	 * 新增流水
	 * @param $storeId
	 * @param $type
	 * @param $orderId
	 * @param $originPrice
	 * @param $realPrice
	 * @param $profit
	 * @param $cost
	 * @param $barber_royalty
	 * @param int $cardDiscount
	 * @param int $discount
	 * @param int $payment
	 * @return mixed
	 */
	public function add($storeId, $userId, $type, $orderId, $originPrice, $realPrice, $profit, $cost, $barber_royalty, $cardDiscount = 0, $discount = 0, $payment = 1)
	{
		return $this->create([
			'store_id'       => $storeId,
			'user_id'        => $userId,
			'category'       => $type,
			'link_id'        => $orderId,
			'original_price' => $originPrice,
			'real_price'     => $realPrice,
			'profit'         => $profit,
			'cost'           => $cost,
			'barber_royalty' => $barber_royalty,
			'card_discount'  => $cardDiscount,
			'discount'       => $discount,
			'payment'        => $payment
		]);
	}

	/**
	 * 计算今日总订单数量
	 * @param $storeId
	 * @param $userId
	 * @return mixed
	 */
	public function getTodayOrderNum($storeId,$userId=0){
		$where['store_id'] = $storeId;
		empty($userId) ? : $where['user_id'] = $userId;
		return $this->model
			->where($where)
			->whereDate('created_at',date('Y-m-d'))
			->count();
	}

	/**
	 * 今日营业额
	 * @param $storeId
	 * @param $userId
	 * @param $dateList
	 * @return mixed
	 */
	public function getTodayTurnOver($storeId,$userId=0,$dateList=[]){
		$where['store_id'] = $storeId;
		empty($userId) ? : $where['user_id'] = $userId;
		$model = $this->model
			->where($where);
		empty($dateList) ? $model->whereDate('created_at',date('Y-m-d')) :
			$model->whereDate('created_at','>=',$dateList['end_date'])
				->whereDate('created_at','<=',$dateList['start_date']);
		return $model->sum('real_price');
	}

	/**
	 * 店铺的销售成本
	 * @param $dateList
	 * @param $storeId
	 * @return mixed
	 */
	public function getStoreCost($dateList,$storeId){
		return $this->model->where(['store_id'=>$storeId])
			->whereDate('created_at','>=',$dateList['end_date'])
			->whereDate('created_at','<=',$dateList['start_date'])
			->sum('cost');
	}


	/**
	 * 获取店铺毛利润
	 * @param $storeId
	 * @param $dateList
	 * @return mixed
	 */
	public function getProfit($storeId,$dateList){
		return $this->model
			->where(['store_id'=>$storeId])
			->whereDate('created_at','>=',$dateList['end_date'])
			->whereDate('created_at','<=',$dateList['start_date'])
			->sum('profit');
	}

	/**
	 * 店长端支付方式概览
	 * @param $dateList
	 * @param $storeId
	 * @return array
	 */
	public function getStorePaymentInfo($dateList, $storeId)
	{
		$list = $this->model
			->selectRaw('sum(hx_amount_flow.real_price) as amount,count(hx_amount_flow.id) as count, hx_amount_flow.payment')
			->leftJoin('payment_type', 'payment_type.id', 'amount_flow.payment')
			->where(['amount_flow.store_id' => $storeId])
			->whereDate('amount_flow.created_at', '>=', $dateList['end_date'])
			->whereDate('amount_flow.created_at', '<=', $dateList['start_date'])
			->groupBy('amount_flow.payment')
			->get()
			->toArray();
		return empty($list) ? $list : array_column($list, null, 'payment');
	}

	/**
	 * 店长端支付方式列表
	 * @param $dateList
	 * @param $storeId
	 * @param $payment
	 * @param int $pageSize
	 * @return \Illuminate\Contracts\Pagination\LengthAwarePaginator
	 */
	public function getStorePaymentList($dateList, $storeId, $payment, $pageSize = 10)
	{
		return $this->model->with([
			'user' => function ($v) {
				$v->select(['id', 'nick', 'portrait'])->with('picture:id,image');
			}
		])
			->where(['store_id' => $storeId, 'payment' => $payment])
			->whereDate('created_at', '>=', $dateList['end_date'])
			->whereDate('created_at', '<=', $dateList['start_date'])
			->paginate($pageSize, ['*'], 'paginate');
	}


	/**
	 * 员工业绩列表
	 * @param $dateList
	 * @param $storeId
	 * @return array
	 */
	public function getStoreAchievement($dateList, $storeId)
	{
		$list = $this->model
			->selectRaw('sum(hx_amount_flow.real_price) as amount,count(hx_amount_flow.id) as count, hx_amount_flow.user_id')
			->where(['store_id' => $storeId])
			->whereDate('created_at', '>=', $dateList['end_date'])
			->whereDate('created_at', '<=', $dateList['start_date'])
			->groupBy('user_id')
			->get()
			->toArray();

		return empty($list) ? $list : array_column($list, null, 'user_id');
	}

	/**
	 * 今日经营数据分析
	 * @param $storeId
	 * @param $date
	 * @param $compareDate
	 * @return mixed
	 */
	public function getAmountRate($storeId, $date, $compareDate)
	{

		return $this->model
			->selectRaw('date(created_at) as dates, round(sum(real_price)/count(id),2) as counts')
			->whereRaw('(store_id=' . $storeId . ' and date(created_at)="' . $date . '")')
			->orWhereRaw('(store_id=' . $storeId . ' and date(created_at)="' . $compareDate . '") group by date(created_at)')
			->get()->toArray();


	}


	public function getAmountCountRate($storeId, $date, $compareDate)
	{

		return $this->model
			->selectRaw('date(created_at) as dates, count(id) as counts')
			->whereRaw('(store_id=' . $storeId . ' and date(created_at)="' . $date . '")')
			->orWhereRaw('(store_id=' . $storeId . ' and date(created_at)="' . $compareDate . '") group by date(created_at)')
			->get()->toArray();


	}

	/**
	 * 理发师订单量排名
	 * @param $storeId
	 * @param $startDate
	 * @param $endDate
	 * @return array
	 */
	public function getOrderRankListByBarberId($storeId, $startDate, $endDate)
	{
		$sql = ' select c.barber_id,c.barber_name,c.username,count(o.`id`) as counts  from (SELECT  DISTINCT u.id as barber_id, u.nick as barber_name, u.username as username,s.`sid` FROM hx_user AS u LEFT JOIN hx_user_store AS s ON u.id = s.uid WHERE s.sid = '.$storeId.') as c
 LEFT JOIN hx_amount_flow AS o ON c.barber_id = o.user_id  and o.`store_id`='.$storeId.'  where  date( o.created_at) <= "'.$startDate.'" and date(o.created_at) >= "'.$endDate.'" GROUP BY o.user_id order by counts desc';

		return DB::select($sql);
	}


	/**
	 * 营业额排名
	 * @param $storeId
	 * @param $startDate
	 * @param $endDate
	 * @return array
	 */
	public function getAmountRankListByBarberId($storeId, $startDate, $endDate)
	{
		$sql = ' select c.barber_id,c.barber_name,c.username,sum(o.`real_price`) as counts  from (SELECT  DISTINCT u.id as barber_id, u.nick as barber_name, u.username as username,s.`sid` FROM hx_user AS u LEFT JOIN hx_user_store AS s ON u.id = s.uid WHERE s.sid = '.$storeId.') as c
 LEFT JOIN hx_amount_flow AS o ON c.barber_id = o.user_id  and o.`store_id`='.$storeId.'  where  date( o.created_at) <= "'.$startDate.'" and date(o.created_at) >= "'.$endDate.'" GROUP BY o.user_id order by counts desc';

		return DB::select($sql);
//        return $this->model
//            ->selectRaw('sum(real_price) as counts,barber_id')
//            ->with(['user'=>function($v){
//               $v->select(['id','nick','portrait'])->with('picture:id,image');
//            }])
//            ->whereRaw('store_id ="' . $storeId . '" and FROM_UNIXTIME(finish_time,\'%Y-%m-%d\') <= "' .$startDate. '" and FROM_UNIXTIME(finish_time,\'%Y-%m-%d\') >="' . $endDate . '"  group by barber_id order by counts desc')
//
//            ->get();
	}

    /**
     * 获取理发师资金流水
     * @param $user_id
     * @param $store_id
     * @param $date
     * @return mixed
     */
    public function getBarberAmountFlow($user_id, $store_id, $end_day)
    {
        return $this->model->where('user_id', $user_id)
            ->whereDate('created_at', '=', $end_day)
            ->where('store_id', $store_id);
    }
    /**
 * 获取理发师资金流水
 * @param $user_id
 * @param $store_id
 * @param $date
 * @return mixed
 */
    public function getBarberAmountFlowMonth($user_id, $store_id, $end_day)
    {
        return $this->model->where('user_id', $user_id)
            ->whereDate('created_at', '>=', $end_day)
            ->where('store_id', $store_id);
    }
    /**
     * 获取理发师到某日之前的分类流水
     * @param $user_id
     * @param $store_id
     * @param $end_day
     */
    public function getBarberAmountFlowGroup($user_id, $store_id, $end_day)
    {
        return $this->model
            ->selectRaw('category,sum(barber_royalty) as royalty , sum(real_price) as amount , count(*) as count')
            ->where('user_id', $user_id)
            ->whereDate('created_at', '>=', $end_day)
            ->where('store_id', $store_id)
            ->groupBy('category')
            ->get();
    }

    public function getBarberMemberCardAmountFlowAnalysis($user_id, $store_id, $end_day)
    {
        $select = [
            'member.face as image',
            'member_card.name as title',
            'member_card_flow.created_at',
            'amount_flow.real_price as amount',
            'amount_flow.barber_royalty as profit'
        ];
        return $this->model
            ->select($select)
            ->leftJoin('member_card_flow','member_card_flow.id','amount_flow.link_id')
            ->leftJoin('member_card','member_card.id','member_card_flow.card_id')
            ->leftJoin('member', 'member_card.member_id', 'member.id')
            ->where('amount_flow.category',2)
	        ->where('amount_flow.user_id', $user_id)
            ->whereDate('amount_flow.created_at', '>=', $end_day)
            ->where('amount_flow.store_id', $store_id);
    }

	/**
	 * @param $storeId
	 * @param $barberId
	 * @param $startDate
	 * @param $endDate
	 * @param $pageSize
	 * @param int $isProfit
	 * @return mixed
	 * @throws \Flower\Core\Repository\Exceptions\RepositoryException
	 */
	public function getOrderServiceList($storeId, $barberId, $startDate, $endDate, $pageSize, $isProfit = 0)
	{
		$pageSize = empty($pageSize) ? 10 : $pageSize;
		return $this->pushCriteria(new getContributionOrderListCriteria($storeId, $barberId, $startDate, $endDate, $isProfit))->paginate($pageSize, ['*'], 'paginate');

	}


	public function getStoreMemberCardAmountFlowAnalysis($store_id, $dateList,$pageSize)
	{
		$select = [
			'member.face as image',
			'member_card.name as title',
			'member_card_flow.created_at',
			'amount_flow.real_price as amount',
			'amount_flow.profit'
		];
		return $this->model
			->select($select)
			->leftJoin('member_card_flow','member_card_flow.id','amount_flow.link_id')
			->leftJoin('member_card','member_card.id','member_card_flow.card_id')
			->leftJoin('member', 'member_card.member_id', 'member.id')
			->where('amount_flow.category',2)
			->whereDate('amount_flow.created_at', '>=', $dateList['end_date'])
			->whereDate('amount_flow.created_at', '<=', $dateList['start_date'])
			->where('amount_flow.store_id', $store_id)
			->paginate($pageSize,['*']);
	}
}